package multiagent

import (
	"anders-cli/internal/ai"
	"anders-cli/internal/config"
	"anders-cli/pkg/logger"
	"fmt"
)

// CreateDefaultAgents 创建默认的子Agent列表
func CreateDefaultAgents(backend ai.Backend) []Agent {
	cfg := config.Get()
	roles := cfg.MultiAgent.Roles

	var agents []Agent

	// 创建业务分析员
	if analystName, exists := roles["analyst"]; exists && analystName != "" {
		if analyst, err := NewBusinessAnalystWithRules(analystName, backend); err == nil {
			agents = append(agents, analyst)
			logger.Info("已创建业务分析员: %s (%s)", analyst.GetName(), analystName)
		} else {
			logger.Error("创建业务分析员失败: %v，使用默认实现", err)
			agents = append(agents, NewBusinessAnalyst(backend))
		}
	} else {
		agents = append(agents, NewBusinessAnalyst(backend))
	}

	// 创建架构师
	if architectName, exists := roles["architect"]; exists && architectName != "" {
		if architect, err := NewArchitectWithRules(architectName, backend); err == nil {
			agents = append(agents, architect)
			logger.Info("已创建架构师: %s (%s)", architect.GetName(), architectName)
		} else {
			logger.Error("创建架构师失败: %v，使用默认实现", err)
			agents = append(agents, NewArchitect(backend))
		}
	} else {
		agents = append(agents, NewArchitect(backend))
	}

	return agents
}

// CreateAgentFromConfig 根据配置创建指定类型的Agent
func CreateAgentFromConfig(roleType string, backend ai.Backend) (Agent, error) {
	cfg := config.Get()
	roles := cfg.MultiAgent.Roles

	characterName, exists := roles[roleType]
	if !exists || characterName == "" {
		return nil, fmt.Errorf("未找到角色配置: %s", roleType)
	}

	switch roleType {
	case "pm":
		pm, err := NewProjectManagerWithRules(characterName, backend, cfg.MultiAgent.MaxFeedbackRounds, cfg.MultiAgent.ConflictThreshold)
		return pm, err
	case "analyst":
		return NewBusinessAnalystWithRules(characterName, backend)
	case "architect":
		return NewArchitectWithRules(characterName, backend)
	default:
		return nil, fmt.Errorf("不支持的角色类型: %s", roleType)
	}
}

// CreateProjectManagerFromConfig 根据配置创建项目管理器
func CreateProjectManagerFromConfig(backend ai.Backend) (*ProjectManager, error) {
	cfg := config.Get()
	roles := cfg.MultiAgent.Roles

	pmName, exists := roles["pm"]
	if !exists || pmName == "" {
		// 使用默认的项目管理器
		return NewProjectManager(backend, cfg.MultiAgent.MaxFeedbackRounds, cfg.MultiAgent.ConflictThreshold), nil
	}

	return NewProjectManagerWithRules(pmName, backend, cfg.MultiAgent.MaxFeedbackRounds, cfg.MultiAgent.ConflictThreshold)
}
